<script setup>
import { computed, reactive, ref, watch,inject } from 'vue'
import { CloseOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue'
import { take } from 'lodash-es'
import moment from 'moment'
import DouyinMusicDrawer from '@/components/ArticlePublish/drawers/douyinMusic.vue'
import dayjs from 'dayjs'
import { useVModel } from "@vueuse/core";
import { Form } from "ant-design-vue"

const { convertTimeToTimezone ,currentTimezone,disabledDate,disabledDateTime,getTimezoneList} = inject('timezone')
const timezones = getTimezoneList()
const currentTimezoneLabel = computed(() => {
  return timezones.find((item) => item.value == currentTimezone.value).label
})
const props = defineProps({
    formData: {
        type: Object,
        default: () => {
            return {
            poster: [],
            challenges: [],
            download: "1",
            music_id: "",
            music_end_time: "",
            visibility_type: "0",
            publish_type: "1",
            fix_at: "",
            utc_offset:'',
            }
        }
    },
    accountId: {
        type:[Number,String],
        required: true
    },
    title: {
        type: String,
        default: ''
    },
    content: {
        type: String,
        default: ''
    },
    isShowPublishTime:{//是否显示发布时间
        type:Boolean,
        default:true
    },
    multiple:{
        type: Boolean,
        default: false
      },
})
let state = reactive({
        publishTime:''
})
let musicIds = ref([])
let musics = ref([])
const musicList = computed(()=>{
return musics.value.map(item=>{
    return {
    value: item.id,
    label: item.title + `(${item.author})`,
    }
})
})
watch(()=>musicList.value,(list)=>{
    if(list.length){
        musicIds.value = list.map(item=>item.value)
    }
},{deep:true})

watch(()=>musicIds.value,(ids)=>{
    formRef.value.music_id = ids
},{deep:true})
const useForm = Form.useForm
const emits = defineEmits(['update:formData'])
const formRef = useVModel(props, 'formData', emits)
formRef.value.utc_offset = currentTimezone.value
let validate_time = () => {

if (formRef.value.publish_type == 2 && !formRef.value.fix_at) {

  return Promise.reject('请选择发布时间');
} else {
  return Promise.resolve();
}
}
const rules = reactive({

        fix_at: [
         {
           required: true,
           validator: validate_time,
           trigger: 'change',
         }
       ],
      })
const { resetFields, validate ,validateInfos} = useForm(formRef, rules)
let materialVisible = ref(false)
const challengeInputVisible = ref(false)
const selectMusic = ref()
const musicDrawerVisible = ref(false)


const onMusicSelected = (music) => {
    if(props.multiple){

          musics.value = [...music]
        }else{
            selectMusic.value = music

          if(music){
            formRef.value.music_id = music.id
            formRef.value.music_end_time = music.duration * 1000
          } else {
            formRef.value.music_id = ''
            formRef.value.music_end_time = ''
          }

        }
}
const musicTitle = computed(() => {
    return selectMusic.value
        ? selectMusic.value.title + `(${selectMusic.value.author})`
        : ''
})
watch(() => props.formData.fix_at, () => {
    if (props.formData.publish_type == 2) {

        state.publishTime = props.formData.fix_at ? moment(props.formData.fix_at) :moment()
    }
}, { deep: true, immediate: true })
const onChallengeChange = (values) => {

    formRef.value.challenges = take(values.filter(value => value.length <= 10), 5)

}
const tagChange = (values)=>{
    musics.value = musics.value.filter(item=>values.includes(item.id))
}
const onTimeChange = (e) => {
  if(!e){
    state.publishTime = null
    formRef.value.fix_at = null
    return
  }
  // const offsetInMinutes = currentTimezone * 60
  //   // 将时间转换为指定时区时间
  // nextTick(()=>{
  //   state.publishTime = dayjs(e).utcOffset(offsetInMinutes)
  // })

  // formRef.value.fix_at = e ? dayjs(e).utcOffset(offsetInMinutes).format('YYYY-MM-DD HH:mm') : null
  state.publishTime = dayjs(e)
  formRef.value.fix_at = e ? dayjs(e).format('YYYY-MM-DD HH:mm') : null
};

const validateData = ()=>{
    return new Promise((resolve, reject) => {
        validate().then(res=>{
            resolve(res)
        }).catch(err=>{
            reject(err)
        })
    })
}
defineExpose({
    validateData,
    musics,
})
</script>

<template>
    <div class="douyin-form">
        <a-form layout="vertical" :rules="rules">
            <a-form-item>
                <template #label>
                    <span class="mr-5">选择音乐--快手</span>
                    <a-tooltip>
                        <template #title>
                            <span>需要先选择账号</span>
                        </template>
                        <QuestionCircleOutlined />
                    </a-tooltip>
                </template>
                <a-input v-if="!multiple" class="cursor-pointer music-input" :disabled="!accountId" :value="musicTitle" :maxlength="20" placeholder="点击选择音乐"
                    @click="musicDrawerVisible = true" readonly>
                    <template #suffix>
                        <CloseOutlined @click="onMusicSelected(null)" />
                    </template>
                </a-input>
                <a-select v-else   @click="!accountId?'':(musicDrawerVisible = true)" :disabled="!accountId" mode="tags"  @change="tagChange" :options="musicList" v-model:value="musicIds"></a-select>
            </a-form-item>
            <a-form-item label="话题">
                <a-select v-model:value="formRef.challenges" mode="tags"
                @change="onChallengeChange"
                   >

                </a-select>
                <div class="fs-12">
                    您可添加5个标签，每个标签不可以超过10个字，按回车键确认
                </div>
            </a-form-item>
            <a-form-item label="允许他人保存图片">
                <a-radio-group v-model:value="formRef.download">
                    <a-radio value="1">允许</a-radio>
                    <a-radio value="0">不允许</a-radio>
                </a-radio-group>
            </a-form-item>
            <a-form-item label="谁可以看">
                <a-radio-group v-model:value="formRef.visibility_type">
                    <a-radio value="0">公开</a-radio>
                    <a-radio value="2">好友可见</a-radio>
                    <a-radio value="1">自己可见</a-radio>
                </a-radio-group>
            </a-form-item>
            <a-form-item label="发布时间" required v-if="isShowPublishTime">
                <a-radio-group v-model:value="formRef.publish_type">
                    <a-radio value="1">立即发布</a-radio>
                    <a-radio value="2">定时发布</a-radio>
                </a-radio-group>
            </a-form-item>
            <a-form-item v-if="formRef.publish_type == 2" v-bind="validateInfos.fix_at">
                <a-date-picker :disabledDate="disabledDate" :disabled-time="disabledDateTime"
                  :value="state.publishTime"
                  :showNow="false"
                  :show-time="{ format: 'YYYY-MM-DD HH:mm' }" format="YYYY-MM-DD HH:mm"
                    placeholder="请选择时间" @change="onTimeChange" />
                    <span class="sys-timezone">（用户设置时区：{{ currentTimezoneLabel }}）</span>
            </a-form-item>
        </a-form>
        <DouyinMusicDrawer 
        v-model:visible="musicDrawerVisible" 
        :musicList="musics" 
        :accountId="accountId" 
        :multiple="multiple" 
        @selected="onMusicSelected"
        >
        </DouyinMusicDrawer>
        <!-- <a-modal :visible="previewVisible" :footer="null" @cancel="() => previewVisible = false">
            <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal> -->
    </div>
</template>

<style lang="less" scoped>
.music-input input {
    cursor: pointer;
}

.ss-form-item-has-error .ss-upload {
    background-color: #fff !important;
    border-color: #ff4d4f !important;
}
.sys-timezone{
  margin-left: 5px;
  color:#aaa;
}
</style>
